//
//  AIShareView.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/31.
//

#import "AIShareView.h"
#import "DashedLineView.h"

@interface AIShareView()

@property(nonatomic,strong)UIView *cutView;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UILabel *contentLabel;
@property(nonatomic,strong)DashedLineView *line;
@property(nonatomic,assign)CGFloat max_h;

@end

@implementation AIShareView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        self.currentAvailableHeight = frame.size.height;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    __weak typeof(self)weakSelf = self;
    
    CGFloat h100 = [DeviceUtils getAdaptedHeightForDesignHeight:100 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat w48 = [DeviceUtils getAdaptedWidthForDesignWidth:48 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w48 > 60){
        w48 = 60;
    }
    CGFloat w54 = [DeviceUtils getAdaptedWidthForDesignWidth:54 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.max_h = self.currentAvailableHeight-h100-w48-24-kYM_STATUSBAR_HEIGHT-10;
    
    self.backgroundColor = UIColorHex_(0x000000,0.8);
    UITapGestureRecognizer *hiddenTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenTap:)];
    [self addGestureRecognizer:hiddenTap];
    
    CGFloat top = (self.max_h-80)/2.0+kYM_STATUSBAR_HEIGHT;
    CGFloat left = (self.currentAvailableWidth-255)/2.0;
    self.cutView = [[UIView alloc]initWithFrame:CGRectMake(left,top,255,80)];
    self.cutView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.cutView];
    
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0,0,255,80)];
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.cutView addSubview:self.bgView];
    
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontPingFangSCRegular(13);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.backgroundColor = [UIColor clearColor];
    [self.bgView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@14);
        make.top.mas_equalTo(@18);
        make.right.mas_equalTo(@-14);
        make.height.mas_equalTo(@0);
    }];
    
    self.line = [[DashedLineView alloc]init];
    self.line.backgroundColor = [UIColor whiteColor];
    [self.bgView addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(14);
        make.height.mas_equalTo(@1);
    }];
    
    self.contentLabel = [[UILabel alloc]init];
    self.contentLabel.font = JPUIFontPingFangSCRegular(12);
    self.contentLabel.textColor = KFontGrayColor;
    self.contentLabel.numberOfLines = 0;
    [self.bgView addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@14);
        make.top.mas_equalTo(weakSelf.line.mas_bottom).offset(12);
        make.right.mas_equalTo(@-14);
        make.bottom.mas_equalTo(@-92);
    }];
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = KbgColor;
    [self.bgView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(@80);
    }];
    UIView *codeBgView = [[UIView alloc]init];
    codeBgView.backgroundColor = [UIColor whiteColor];
    codeBgView.layer.cornerRadius = 6;
    codeBgView.layer.masksToBounds = YES;
    codeBgView.layer.borderWidth = 1;
    codeBgView.layer.borderColor = KThemeColor.CGColor;
    [bottomView addSubview:codeBgView];
    [codeBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@52);
        make.bottom.mas_equalTo(@-14);
        make.left.mas_equalTo(@14);
    }];
    UIImageView *codeImageView = [[UIImageView alloc]init];
    UIImage *codeImage =  [self createNonInterpolatedUIImageFormCIImage:[self createhnfgjQRcodedjgkgkWithUrlstring:SHARELINK] withSize:44];
    if(codeImage){
        codeImageView.image = codeImage;
    }
    [codeBgView addSubview:codeImageView];
    [codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@44);
        make.centerX.mas_equalTo(codeBgView);
        make.centerY.mas_equalTo(codeBgView);
    }];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.font = JPUIFontPingFangSCRegular(12);
    tipLabel.textColor = KFontBlackColor;
    tipLabel.text = @"有日语问题，问小岛";
    [bottomView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(codeBgView.mas_right).offset(14);
        make.height.mas_equalTo(@17);
        make.top.mas_equalTo(codeBgView.mas_top).offset(6);
    }];
    UILabel *tipLabel2 = [[UILabel alloc]init];
    tipLabel2.font = JPUIFontPingFangSCRegular(12);
    tipLabel2.textColor = KFontGrayColor;
    tipLabel2.text = @"来自 日语岛";
    [bottomView addSubview:tipLabel2];
    [tipLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(codeBgView.mas_right).offset(14);
        make.height.mas_equalTo(@17);
        make.top.mas_equalTo(tipLabel.mas_bottom).offset(6);
    }];
    
    NSArray *titleArr = @[@"微信好友",@"朋友圈",@"保存图片"];
    NSArray *imageArr = @[@"word_checkin_wechat",@"word_checkin_wechat_cycle",@"word_checkin_download"];
    CGFloat redix = (self.currentAvailableWidth-w48*3-w54*2)/2.0;
    for(NSInteger i = 0;i < titleArr.count;i++){
        UIButton *btn = [[UIButton alloc]init];
        btn.backgroundColor = UIColorHex_(0xffffff,0.2);
        btn.layer.cornerRadius = w48/2.0;
        btn.layer.masksToBounds = YES;
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        btn.tag = 100+i;
        [btn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(w48);
            make.left.mas_equalTo(w54+i*(w48+redix));
            make.bottom.mas_equalTo(-h100-24);
        }];
        UILabel *shareLabel = [[UILabel alloc]init];
        shareLabel.font = JPUIFontPingFangSCRegular(13);
        shareLabel.textColor = UIColorHex_(0xffffff,0.5);
        shareLabel.textAlignment = NSTextAlignmentCenter;
        shareLabel.userInteractionEnabled = YES;
        shareLabel.text = titleArr[i];
        shareLabel.tag = 200+i;
        [self addSubview:shareLabel];
        [shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@18);
            make.top.mas_equalTo(btn.mas_bottom).offset(6);
            make.centerX.mas_equalTo(btn);
            make.width.mas_equalTo(@52);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf shareClickWithIndex:i];
        }];
        [shareLabel addGestureRecognizer:tap];
    }
}

-(void)refreshWidth{
    CGFloat h100 = [DeviceUtils getAdaptedHeightForDesignHeight:100 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat w48 = [DeviceUtils getAdaptedWidthForDesignWidth:48 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w48 > 60){
        w48 = 60;
    }
    CGFloat w54 = [DeviceUtils getAdaptedWidthForDesignWidth:54 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.max_h = self.currentAvailableHeight-h100-w48-24-kYM_STATUSBAR_HEIGHT-10;
    CGFloat top = (self.max_h-80)/2.0+kYM_STATUSBAR_HEIGHT;
    CGFloat left = (self.currentAvailableWidth-255)/2.0;
    self.cutView.frame = CGRectMake(left,top,255,80);
    CGFloat redix = (self.currentAvailableWidth-w48*3-w54*2)/2.0;
    for(NSInteger i = 0;i < 3;i++){
        UIButton *btn = [self viewWithTag:100+i];
        btn.layer.cornerRadius = w48/2.0;
        [btn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(w48);
            make.left.mas_equalTo(w54+i*(w48+redix));
            make.bottom.mas_equalTo(-h100-24);
        }];
        UILabel *shareLabel = [self viewWithTag:200+i];
        [shareLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(btn.mas_bottom).offset(6);
            make.centerX.mas_equalTo(btn);
        }];
    }
    CGSize t_size = [self.titleLabel sizeThatFits:CGSizeMake(227,MAXFLOAT)];
    CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(227,MAXFLOAT)];
    CGFloat b_h = 80+57+t_size.height+c_size.height;
    if(b_h > self.max_h){
        b_h = self.max_h;
    }
    if(((b_h+top*2)> self.currentAvailableHeight)&&((self.currentAvailableHeight - b_h)/2.0 < top)){
        top = (self.currentAvailableHeight - b_h)/2.0;
    }
    self.cutView.frame = CGRectMake(left,top,255,b_h);
    self.bgView.frame = CGRectMake(0,0,255,b_h);
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(t_size.height);
    }];
    __weak typeof(self)weakSelf = self;
    [self.line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(14);
    }];
    [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.line.mas_bottom).offset(12);
    }];
}

-(void)setModel:(AIListModel *)model{
    _model = model;
    self.titleLabel.text = model.sendContent;
    self.contentLabel.text = model.receiveContent;
    CGSize t_size = [self.titleLabel sizeThatFits:CGSizeMake(227,MAXFLOAT)];
    CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(227,MAXFLOAT)];
    CGFloat b_h = 80+57+t_size.height+c_size.height;
    if(b_h > self.max_h){
        b_h = self.max_h;
    }
    CGFloat top = (self.max_h-b_h)/2.0+kYM_STATUSBAR_HEIGHT;
    CGFloat left = (self.currentAvailableWidth-255)/2.0;
    if(((b_h+top*2)> self.currentAvailableHeight)&&((self.currentAvailableHeight - b_h)/2.0 < top)){
        top = (self.currentAvailableHeight - b_h)/2.0;
    }
    self.cutView.frame = CGRectMake(left,top,255,b_h);
    self.bgView.frame = CGRectMake(0,0,255,b_h);
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(t_size.height);
    }];
    __weak typeof(self)weakSelf = self;
    [self.line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(14);
    }];
    [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.line.mas_bottom).offset(12);
    }];
}

#pragma mark - 隐藏点击
- (void)hiddenTap:(UITapGestureRecognizer *)gesture {
    CGPoint touchPoint = [gesture locationInView:self];
    // 判断点击位置是否在UIImageView内
    if (!CGRectContainsPoint(self.bgView.frame,touchPoint)) {
        // 点击位置不在UIImageView内，执行相应操作
        [self removeFromSuperview];
    }
}

#pragma mark - 分享点击
-(void)shareClick:(UIButton*)btn{
    NSInteger index = btn.tag-100;
    [self shareClickWithIndex:index];
}

-(void)shareClickWithIndex:(NSInteger)index{
    if(index == 0||index == 1){
        self.cutView.backgroundColor = UIColorHex_(0x000000,0.8);
        UIImage *lastImage = [self captureScreenForView:self.cutView];
        self.cutView.backgroundColor = [UIColor clearColor];
        if(_shareBlock){
            _shareBlock(index,lastImage);
        }
    }else{
        //保存图片
        __weak typeof(self)self_weak_ = self;
        [self isCanVisitPhotoLibrary:^(BOOL iscan) {
            if (iscan == YES) {
                [self_weak_ saveConfig];
            }else{
                [JPProgressHUD showMsg:@"未开启相册权限，请到设置中开启"];
            }
        }];
    }
}

#pragma mark - 保存截图
-(void)saveConfig{
    self.cutView.backgroundColor = UIColorHex_(0x000000,0.8);
    UIImage *lastImage = [self captureScreenForView:self.cutView];
    if(lastImage){
        UIImageWriteToSavedPhotosAlbum(lastImage,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
    }
}

#pragma mark - 图片保存状态
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    self.cutView.backgroundColor = [UIColor clearColor];
    if (error == nil) {
        [JPProgressHUD showMsg:@"保存成功"];
    }else{
        [JPProgressHUD showMsg:@"保存失败"];
    }
}

#pragma mark - 获取底部截屏图片
- (UIImage *)captureScreenForView:(UIView *)currentView{
    if (CGRectIsEmpty(currentView.bounds)) {
        // 当前视图的尺寸为零，无法进行截图
        return nil;
    }
    // 开启一个绘图的上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(currentView.size.width, currentView.size.height), NO,0.0);
    // 作用于CALayer层的方法。将view的layer渲染到当前的绘制的上下文中。
    [currentView drawViewHierarchyInRect:CGRectMake(0, 0, currentView.frame.size.width, currentView.frame.size.height) afterScreenUpdates:YES];
    // 获取图片
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束绘图上下文
    UIGraphicsEndImageContext();
    
    return  viewImage;
}


#pragma mark - 生成二维码
-(CIImage *)createhnfgjQRcodedjgkgkWithUrlstring:(NSString *)urlString{
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKeyPath:@"inputCorrectionLevel"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return outputImage;
}


- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

#pragma mark - 相册权限检测
-(void)isCanVisitPhotoLibrary:(void(^)(BOOL))result{
   PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
   if (status == PHAuthorizationStatusAuthorized) {
       result(YES);
       return;
   }
   if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
       result(NO);
       return ;
   }
   
   if (status == PHAuthorizationStatusNotDetermined) {
       
       [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
           // 回调是在子线程的
//           NSLog(@"%@",[NSThread currentThread]);
           dispatch_async(dispatch_get_main_queue(), ^{
               if (status != PHAuthorizationStatusAuthorized) {
//                     NSLog(@"未开启相册权限,请到设置中开启");
                     result(NO);
                     return ;
                 }
                 result(YES);
           });
 
       }];
   }
   
}


@end
